package com.kedacom.demo.rabbitmq_java_client.ch2.workqueues;

import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class Worker {

	public static void main(String[] argv)
			throws java.io.IOException, java.lang.InterruptedException, TimeoutException {

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(Constants.RABBITMQ_HOST);
		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();

		int prefetchCount = 1;
		channel.basicQos(prefetchCount);

		final boolean durable = true;
		channel.queueDeclare(Constants.QUEUE_NAME, durable, false, false, null);
		System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

		QueueingConsumer consumer = new QueueingConsumer(channel);
		final boolean autoAck = false;
		channel.basicConsume(Constants.QUEUE_NAME, autoAck, consumer);

		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			System.out.println(" [x] Received '" + message + "'");
			SimpleTask task = SimpleTask.fromJson(message);
			Thread.sleep(1000 * task.getSecondsWillBeTaken());
			System.out.println(" [x] Done");
			channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
		}
	}

}
